package com.zhz.lib.cms.manage.quanxian;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.zhz.project.common.util.hibernate.BaseDAO;
import com.zhz.lib.cms.domain.quanxian.GroupAuthorities;
import com.zhz.lib.cms.domain.quanxian.GroupMembers;
import com.zhz.lib.cms.domain.quanxian.Groups;
import com.zhz.lib.cms.domain.quanxian.User;
import com.zhz.lib.cms.security.resource.ResourceDetailsMonitor;
import com.zhz.project.common.util.zhzutil.ZhzHttpRequestUtil;
import com.zhz.project.common.util.zhzutil.ZhzStringUtil;
import com.zhz.project.common.util.alibaba.StringUtil;

public class quanxianAction extends DispatchAction {

	private BaseDAO baseDao;
	private Integer pageSize;
	private TransactionTemplate transactionTemplate;

	/**
	 * 不给参数，默认执行此处
	 */
	public ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		return userlist(mapping, form, request, response);
	}

	// //////////////////////////////////////////////////////////////
	// 下面是有关用户的相关操作
	// //////////////////////////////////////////////////////////////

	/**
	 * 显示用户列表
	 */
	@SuppressWarnings("unchecked")
	public ActionForward userlist(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String selectedoption = ZhzHttpRequestUtil.getParameters(request,
				"selectedoption");

		String keywordType = ZhzHttpRequestUtil.getParameters(request,
				"keywordType");
		String keyword = ZhzHttpRequestUtil.getParameters(request, "keyword");
		String keywordOut = null;
		if (StringUtil.isNotBlank(keyword)) {
			keyword = URLDecoder.decode(keyword);
			keywordOut = URLEncoder.encode(URLEncoder.encode(keyword));
		}

		String pageNowString = null;
		int pageNow = 0;
		String pageSizeString = null;
		int pageSize = 1;
		pageNowString = request.getParameter("pageNow");
		pageSizeString = request.getParameter("pageSize");

		if (ZhzStringUtil.isNotNull(pageNowString)) {
			pageNow = Integer.parseInt(pageNowString.trim());
		} else {
			pageNow = 1;
		}
		if (ZhzStringUtil.isNotNull(pageSizeString)) {
			pageSizeString = pageSizeString.trim();
		} else {
			pageSize = this.pageSize;
		}
		if (pageNow <= 1)
			pageNow = 1;

		int entryTatal = 0;
		String whereStatement = null;

		if (ZhzStringUtil.isNotNull(keyword)) {
			entryTatal = baseDao.getNumOnQuery(" FROM  User  where "
					+ keywordType + " like '%" + keyword + "%'");
			whereStatement = " where " + keywordType + " like '%" + keyword
					+ "%'";
		} else {

			entryTatal = baseDao.getNumOnQuery(" FROM  User");
			whereStatement = "";
		}
		List<User> userlist = baseDao.findAllByPage("User", whereStatement,
				"order by id DESC", pageNow, pageSize);

		if (ZhzStringUtil.isNotNull(selectedoption)) {
			entryTatal = baseDao
					.getNumOnQuery(" FROM GroupMembers  where groupId='"
							+ selectedoption + "'");

			whereStatement = "where groupId='" + selectedoption + "'";

			List<GroupMembers> gmlist = baseDao.findAllByPage("GroupMembers",
					whereStatement, "order by groupId", pageNow, pageSize);

			List<User> tempList = new ArrayList<User>();

			for (GroupMembers gm : gmlist) {

				User user = (User) baseDao.findOneObject("User", "username", gm
						.getUsername());
				tempList.add(user);

			}
			userlist = tempList;

		}
		List<UserGroupsVO> uglist = new ArrayList<UserGroupsVO>();
		for (User user : userlist) {
			GroupMembers gm = (GroupMembers) baseDao.findOneObject(
					"GroupMembers", "username", user.getUsername());
			Groups g = null;
			if (null != gm)
				g = (Groups) baseDao.findOneObject("Groups", "id", gm
						.getGroupId().toString());
			UserGroupsVO userGroupsVO = new UserGroupsVO();
			userGroupsVO.setUser(user);
			userGroupsVO.setGroups(g);
			uglist.add(userGroupsVO);

		}

		if (whereStatement == null)
			whereStatement = "";
		int pageTatal = 0;
		if (0 == entryTatal % pageSize) {
			pageTatal = entryTatal / pageSize;
		} else {
			pageTatal = entryTatal / pageSize + 1;
		}

		if (pageNow > pageTatal) {
			pageNow = pageTatal;
		}

		request.setAttribute("pageNow", pageNow);
		request.setAttribute("pageSize", pageSize);
		request.setAttribute("pageTatal", pageTatal);
		request.setAttribute("entryTatal", entryTatal);
		request.setAttribute("keyword", keywordOut);
		request.setAttribute("keywordType", keywordType);
		request.setAttribute("selectedoption", selectedoption);
		request.setAttribute("uglist", uglist);
		request.setAttribute("group_arraylist", getGroupList());
		return mapping.findForward("user-list");
	}

	/**
	 * 添加用户
	 */
	public ActionForward useradd(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		request.setAttribute("group_list", getGroupList());

		return mapping.findForward("user-add");

	}

	/**
	 * 保存新添加的用户
	 */
	public ActionForward usersave(ActionMapping mapping, ActionForm form,
			final HttpServletRequest request, HttpServletResponse response) {

		String username = ZhzHttpRequestUtil.getParameters(request, "username");

		String password = ZhzHttpRequestUtil.getParameters(request, "password");

		String name = ZhzHttpRequestUtil.getParameters(request, "name");

		String email = ZhzHttpRequestUtil.getParameters(request, "email");

		String group = ZhzHttpRequestUtil.getParameters(request, "group");

		final User user = new User();
		user.setUsername(username);
		user.setName(name);
		user.setEmail(email);
		user.setStatus(0);
		user.setPassword(password);
		final GroupMembers gm = new GroupMembers();
		gm.setUsername(username);
		gm.setGroupId(Integer.parseInt(group));

		String adduserresult = (String) transactionTemplate
				.execute(new TransactionCallback() {
					public Object doInTransaction(TransactionStatus status) {
						try {
							baseDao.save(user);
							baseDao.save(gm);
						} catch (Exception e) {
							status.setRollbackOnly();
							return null;
						}
						return "adduserresult";
					}

				});

		if (ZhzStringUtil.isNotNull(adduserresult)) {

			request.setAttribute("adduser", "adduser");
			request.setAttribute("adduserresult", adduserresult);
		}
		/**
		 * 返回
		 */

		return mapping.findForward("user-result");
	}

	/**
	 * 编辑用户信息
	 */
	public ActionForward useredit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		String id = ZhzHttpRequestUtil.getParameters(request, "id");
		String username = ZhzHttpRequestUtil.getParameters(request, "username");

		User user = (User) baseDao.findOneObject("User", "id", id);

		GroupMembers gm = (GroupMembers) baseDao.findOneObject("GroupMembers",
				"username", username);
		Groups g = null;
		if (null != gm)
			g = (Groups) baseDao.findOneObject("Groups", "id", gm.getGroupId()
					.toString());

		request.setAttribute("user", user);
		request.setAttribute("groups", g);
		request.setAttribute("group_list", getGroupList());

		return mapping.findForward("user-edit");
	}

	/**
	 * 保存编辑后的用户
	 */
	public ActionForward usereditsave(ActionMapping mapping, ActionForm form,
			final HttpServletRequest request, HttpServletResponse response) {

		final String id = ZhzHttpRequestUtil.getParameters(request, "id");

		final String username = ZhzHttpRequestUtil.getParameters(request,
				"username");

		final String password = ZhzHttpRequestUtil.getParameters(request,
				"password");

		final String name = ZhzHttpRequestUtil.getParameters(request, "name");

		final String email = ZhzHttpRequestUtil.getParameters(request, "email");

		final String group = ZhzHttpRequestUtil.getParameters(request, "group");

		String edituserresult = (String) transactionTemplate
				.execute(new TransactionCallback() {
					public Object doInTransaction(TransactionStatus status) {
						try {
							User user = (User) baseDao.findOneObject("User",
									"id", id);
							GroupMembers gm = (GroupMembers) baseDao
									.findOneObject("GroupMembers", "username",
											user.getUsername());
							user.setUsername(username);
							user.setName(name);
							user.setEmail(email);
							user.setPassword(password);
							baseDao.update(user);

							// 新添加的用户不属于任何用户组
							if (gm == null) {
								GroupMembers gmnew = new GroupMembers();
								gmnew.setUsername(username);
								gmnew.setGroupId(Integer.parseInt(group));
								baseDao.save(gmnew);
							}
							// 已经存在的用户
							else {
								gm.setGroupId(Integer.parseInt(group));
								gm.setUsername(username);
								baseDao.update(gm);

							}

						} catch (Exception e) {
							status.setRollbackOnly();
							return null;
						}
						return "edituserresult";
					}

				});

		if (ZhzStringUtil.isNotNull(edituserresult)) {
			request.setAttribute("edituser", "edituser");
			request.setAttribute("edituserresult", edituserresult);
		}
		/**
		 * 返回
		 */

		return mapping.findForward("user-result");
	}

	/**
	 * 删除用户
	 */
	public ActionForward userdel(ActionMapping mapping, ActionForm form,
			final HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String id = ZhzHttpRequestUtil.getParameters(request, "id");
		final String finalID = id;

		String username = ZhzHttpRequestUtil.getParameters(request, "username");
		final String finalUserName = username;

		String deluserresult = (String) transactionTemplate
				.execute(new TransactionCallback() {

					public Object doInTransaction(TransactionStatus status) {

						try {

							baseDao.delete("User", "id", finalID);
							baseDao.delete("GroupMembers", "username",
									finalUserName);

						} catch (Exception e) {
							status.setRollbackOnly();
							return null;
						}
						return "deluserresult";
					}
				});

		if (ZhzStringUtil.isNotNull(deluserresult)) {

			request.setAttribute("deluser", "deluser");
			request.setAttribute("deluserresult", deluserresult);
		}
		return mapping.findForward("user-result");
	}

	/**
	 * 审核用户
	 */
	@SuppressWarnings("unchecked")
	public ActionForward userApprove(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		Enumeration test = request.getParameterNames();
		String name = null;
		boolean approveResult = false;
		// 0 未审核 1 通过 2 不通过
		String aproveState = request.getParameter("approveState").trim();
		int apoveStateInt = Integer.parseInt(aproveState);
		TreeMap<String, Integer> userIdMap = new TreeMap<String, Integer>();

		while (test.hasMoreElements()) {
			name = (String) test.nextElement();
			name = name.trim();
			String value = request.getParameter(name);
			if (name.contains("checkbox")) {// 将含有值的checkbox，赋值
				userIdMap.put(value, apoveStateInt);
			}
		}

		Iterator it = userIdMap.entrySet().iterator();
		while (it.hasNext()) {
			// entry的输出结果如key0=value0等
			Map.Entry entry = (Map.Entry) it.next();
			String key = (String) entry.getKey();
			User user = (User) baseDao.findOneObject("User", "id", key);
			user.setStatus(apoveStateInt);
			approveResult = baseDao.update(user);
		}

		if (approveResult) {
			request.setAttribute("approveResult", approveResult);
			request.setAttribute("app", "app");
		}
		return mapping.findForward("user-result");
	}

	// 上面是有关用户的相关操作
	// //////////////////////////////////////////////////////////////

	// //////////////////////////////////////////////////////////////
	// 下面是有关用户组的相关操作

	/**
	 * 显示用户组列表
	 */
	@SuppressWarnings("unchecked")
	public ActionForward grouplist(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String keyword = ZhzHttpRequestUtil.getParameters(request, "keyword");

		String keywordType = ZhzHttpRequestUtil.getParameters(request,
				"keywordType");

		String pageNowString = null;
		int pageNow = 0;
		String pageSizeString = null;
		int pageSize = 1;
		pageNowString = request.getParameter("pageNow");
		pageSizeString = request.getParameter("pageSize");

		if (ZhzStringUtil.isNotNull(pageNowString)) {
			pageNow = Integer.parseInt(pageNowString.trim());
		} else {
			pageNow = 1;
		}
		if (ZhzStringUtil.isNotNull(pageSizeString)) {
			pageSizeString = pageSizeString.trim();
		} else {
			pageSize = this.pageSize;
		}
		if (pageNow <= 1)
			pageNow = 1;
		int entryTatal = 0;
		String whereStatement = null;

		if (ZhzStringUtil.isNotNull(keyword)) {
			entryTatal = baseDao.getNumOnQuery(" FROM Groups where "
					+ keywordType + " like '%" + keyword + "%'");
			whereStatement = "where " + keywordType + " like '%" + keyword
					+ "%'";
		} else {

			entryTatal = baseDao.getNumOnQuery(" FROM Groups");
			whereStatement = "";
		}

		if (whereStatement == null)
			whereStatement = "";
		int pageTatal = 0;
		if (0 == entryTatal % pageSize) {
			pageTatal = entryTatal / pageSize;
		} else {
			pageTatal = entryTatal / pageSize + 1;
		}

		if (pageNow > pageTatal) {
			pageNow = pageTatal;
		}
		request.setAttribute("pageNow", pageNow);
		request.setAttribute("pageSize", pageSize);
		request.setAttribute("pageTatal", pageTatal);
		request.setAttribute("entryTatal", entryTatal);
		request.setAttribute("keyword", keyword);
		request.setAttribute("keywordType", keywordType);

		List<Groups> grouplist = baseDao.findAllByPage("Groups",
				whereStatement, "order by id DESC", pageNow, pageSize);

		request.setAttribute("grouplist", grouplist);

		return mapping.findForward("group-list");
	}

	/**
	 * 添加用户组
	 */
	public ActionForward groupadd(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		return mapping.findForward("group-add");

	}

	/**
	 * 保存新添加的用户组
	 */
	@SuppressWarnings("unchecked")
	public ActionForward groupsave(ActionMapping mapping, ActionForm form,
			final HttpServletRequest request, HttpServletResponse response) {

		final String groupName = ZhzHttpRequestUtil.getParameters(request,
				"groupName");
		List<Groups> galistList = baseDao
				.find("Groups", "groupName", groupName);
		if (galistList != null)
			if (galistList.size() > 0) {
				request.setAttribute("groupalreadyexist", "groupalreadyexist");
				return mapping.findForward("quanxian-result");
			}
		String descn = ZhzHttpRequestUtil.getParameters(request, "descn");

		final Groups group = new Groups();
		group.setGroupName(groupName);
		group.setDescn(descn);
		final String[] quanxian = request.getParameterValues("quanxian");

		String addgroupresult = (String) transactionTemplate
				.execute(new TransactionCallback() {
					public Object doInTransaction(TransactionStatus status) {
						try {
							baseDao.save(group);
							Groups group = (Groups) baseDao.findOneObject(
									"Groups", "groupName", groupName);
							// 为用户组赋予新的权限
							for (String role : quanxian) {
								GroupAuthorities ga = new GroupAuthorities();
								ga.setGroupId(group.getId());
								ga.setAuthority(role);
								baseDao.save(ga);
							}
							// 菜单权需要赋予
							GroupAuthorities ga = new GroupAuthorities();
							ga.setGroupId(group.getId());
							ga.setAuthority("ROLE_MENU");
							baseDao.save(ga);

						} catch (Exception e) {
							status.setRollbackOnly();
							return null;
						}
						return "addgroupresult";
					}

				});

		if (ZhzStringUtil.isNotNull(addgroupresult)) {

			request.setAttribute("addgroup", "addgroup");
			request.setAttribute("addgroupresult", addgroupresult);
		}
		/**
		 * 返回
		 */

		return mapping.findForward("group-result");
	}

	/**
	 * 编辑用户组信息
	 */
	@SuppressWarnings("unchecked")
	public ActionForward groupview(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		String id = ZhzHttpRequestUtil.getParameters(request, "id");

		Groups group = (Groups) baseDao.findOneObject("Groups", "id", id);

		List<GroupAuthorities> gaList = baseDao.find("GroupAuthorities",
				"groupId", id);
		if (gaList != null) {
			for (GroupAuthorities ga : gaList) {
				request.setAttribute(ga.getAuthority(), ga.getAuthority());
			}

		}
		request.setAttribute("group", group);
		return mapping.findForward("group-view");
	}

	/**
	 * 编辑用户组信息
	 */
	@SuppressWarnings("unchecked")
	public ActionForward groupedit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		String id = ZhzHttpRequestUtil.getParameters(request, "id");

		Groups group = (Groups) baseDao.findOneObject("Groups", "id", id);

		List<GroupAuthorities> gaList = baseDao.find("GroupAuthorities",
				"groupId", id);
		if (gaList != null) {
			for (GroupAuthorities ga : gaList) {
				request.setAttribute(ga.getAuthority(), ga.getAuthority());
			}

		}

		request.setAttribute("group", group);
		return mapping.findForward("group-edit");
	}

	/**
	 * 保存编辑后的用户组
	 */
	public ActionForward groupeditsave(ActionMapping mapping, ActionForm form,
			final HttpServletRequest request, HttpServletResponse response) {

		final String id = ZhzHttpRequestUtil.getParameters(request, "id");

		final String groupName = ZhzHttpRequestUtil.getParameters(request,
				"groupName");
		final String descn = ZhzHttpRequestUtil.getParameters(request, "descn");

		final String[] quanxian = request.getParameterValues("quanxian");

		String editgroupresult = (String) transactionTemplate
				.execute(new TransactionCallback() {
					public Object doInTransaction(TransactionStatus status) {
						try {
							Groups group = (Groups) baseDao.findOneObject(
									"Groups", "id", id);
							group.setGroupName(groupName);
							group.setDescn(descn);
							// 更新用户组信息
							baseDao.update(group);

							// 删除用户组原有的权限
							baseDao
									.execute("delete from GroupAuthorities ga where ga.groupId='"
											+ id + "'");

							// 为用户组赋予新的权限
							for (String role : quanxian) {
								GroupAuthorities ga = new GroupAuthorities();
								ga.setGroupId(Integer.parseInt(id));
								ga.setAuthority(role);
								baseDao.save(ga);
							}
							// 菜单权需要赋予
							GroupAuthorities ga = new GroupAuthorities();
							ga.setGroupId(Integer.parseInt(id));
							ga.setAuthority("ROLE_MENU");
							baseDao.save(ga);

							refresh(request);

						} catch (Exception e) {
							status.setRollbackOnly();
							return null;
						}
						return "editgroupresult";
					}

				});

		if (ZhzStringUtil.isNotNull(editgroupresult)) {
			request.setAttribute("editgroup", "editgroup");
			request.setAttribute("editgroupresult", editgroupresult);
		}
		/**
		 * 返回
		 */

		return mapping.findForward("group-result");
	}

	/**
	 * 删除用户组
	 */
	public ActionForward groupdel(ActionMapping mapping, ActionForm form,
			final HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String id = ZhzHttpRequestUtil.getParameters(request, "id");
		final String finalId = id;
		String delgroupresult = (String) transactionTemplate
				.execute(new TransactionCallback() {
					@SuppressWarnings("unchecked")
					public Object doInTransaction(TransactionStatus status) {
						try {
							baseDao.delete("Groups", "id", finalId);
							List<GroupMembers> gmlist = baseDao.find(
									"GroupMembers", "groupId", finalId);
							if (gmlist != null)
								for (GroupMembers gm : gmlist) {
									gm.setGroupId(0);
									baseDao.update(gm);
								}
						} catch (Exception e) {
							status.setRollbackOnly();
							return null;
						}
						refresh(request);
						return "delgroupresult";
					}
				});

		if (ZhzStringUtil.isNotNull(delgroupresult)) {
			request.setAttribute("delgroup", "delgroup");
			request.setAttribute("delgroupresult", delgroupresult);
		}
		return mapping.findForward("group-result");
	}

	// //////////////////////////////////////////////////////////////
	// 上面是有关用户组的相关操作
	// 下面是私有函数
	// //////////////////////////////////////////////////////////////
	/**
	 * 刷新数据
	 * */
	private void refresh(HttpServletRequest request) {
		WebApplicationContext ctx = WebApplicationContextUtils
				.getWebApplicationContext(request.getSession()
						.getServletContext());
		ResourceDetailsMonitor rdm = (ResourceDetailsMonitor) ctx
				.getBean("resourceDetailsMonitor");
		rdm.afterPropertiesSet();

	}

	/**
	 * 得到所有用户组的列表
	 * */
	@SuppressWarnings("unchecked")
	private List getGroupList() {
		ArrayList<String[]> group_list = new ArrayList<String[]>();
		List downlistgroup = baseDao.list("Groups");
		String[] groupArray = null;
		// 遍历元素，存于 ArrayList中
		int i = 0;
		for (Iterator it = downlistgroup.iterator(); it.hasNext();) {
			Groups group = (Groups) it.next();
			groupArray = new String[2];
			groupArray[0] = Integer.toString(group.getId());
			groupArray[1] = group.getGroupName();
			group_list.add(groupArray);
			i++;
		}
		return group_list;
	}

	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}

	public void setBaseDao(BaseDAO baseDao) {
		this.baseDao = baseDao;
	}

	public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
		this.transactionTemplate = transactionTemplate;
	}
}